package com.lottery.im.module.service.ui;

import android.app.DatePickerDialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.api.ApiClient;
import com.lottery.im.api.observer.ShowTipListObserver;
import com.lottery.im.api.result.entity.integral.AccType;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * A simple {@link Fragment} subclass.
 */
public class UserCashFilterFragment extends Fragment {

  @BindView(R.id.gridView) GridView gridView;
  Unbinder unbinder;

  @BindView(R.id.tv_timestart) TextView tvTimestart;
  @BindView(R.id.tv_timeend) TextView tvTimeend;
  private Calendar mCalendar;
  private String startDate;
  private String endDate;
  private MyGridViewAdapter mAdapter;
  private List<AccType>mList;

  public UserCashFilterFragment() {
    // Required empty public constructor
  }

  public interface ConfirmListener{
    void onConfirmListener(String startDate,String endDate,String accEn);

    void resetClickListener();
  }
  private ConfirmListener mConfirmListener;
  public void setOnConfrimListener(ConfirmListener listener){
    mConfirmListener=listener;
  }
  public void setOnResetClickListener(){
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_user_cash_filter, container, false);
    unbinder = ButterKnife.bind(this, view);

    tvTimestart.setText(getCurrentDate());
    tvTimeend.setText(getCurrentDate());

    gridView.setOnItemClickListener((adapterView, view1, i, l) -> mAdapter.setCurrentPosition(i));

    String token = MyApplication.getInstance().getToken();
    String userId = MyApplication.getInstance().getUserInfo().getUserId();
    ApiClient.getApiRetrofitInstance()
        .queryAccTypeNameList(userId,token)
        .throttleFirst(2, TimeUnit.SECONDS)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new ShowTipListObserver<AccType>(getActivity()) {
          @Override public void onSuccess(List<AccType> t) {
            mAdapter = new MyGridViewAdapter(mList=t);
            gridView.setAdapter(mAdapter);
          }
        });

    return view;
  }

  private String getCurrentDate() {
    mCalendar = Calendar.getInstance();
    int year = mCalendar.get(Calendar.YEAR);
    int month = mCalendar.get(Calendar.MONTH)+1;
    int day = mCalendar.get(Calendar.DAY_OF_MONTH);
    String smonth=month>=10?String.valueOf(month):"0"+String.valueOf(month);
    String sdate=day>=10?String.valueOf(day):"0"+String.valueOf(day);
    startDate=endDate=year+smonth+sdate;
    return year + "-" + smonth + "-" + sdate;
  }

  @RequiresApi(api = Build.VERSION_CODES.N)
  @OnClick({ R.id.tv_timestart, R.id.tv_timeend, R.id.btn_cancel, R.id.btn_confirm })
  public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.tv_timestart:
        setDateView(tvTimestart);
        break;
      case R.id.tv_timeend:
        setDateView(tvTimeend);
        break;
      case R.id.btn_cancel://重置
        tvTimestart.setText(getCurrentDate());
        tvTimeend.setText(getCurrentDate());
        mAdapter.setCurrentPosition(0);
        mConfirmListener.resetClickListener();
        break;
      case R.id.btn_confirm:
        mConfirmListener.onConfirmListener(startDate,endDate,mList.get(mAdapter.getCurrentPosition()).getAccEN());
        break;
    }
  }

  private void setDateView(TextView textView) {
    DatePickerDialog pickerDialog = new DatePickerDialog(getActivity(), DatePickerDialog.THEME_HOLO_LIGHT,
        (datePicker, i, i1, i2) -> {
          String month=i1+1>=10?String.valueOf(i1+1):"0"+String.valueOf(i1+1);
          String date=i2>=10?String.valueOf(i2):"0"+String.valueOf(i2);
          textView.setText(i+"-"+month+"-"+date);
          if(textView.getId()==R.id.tv_timestart){
            startDate=i+""+month+""+date;
          }else{
            endDate=i+""+month+""+date;
          }
        }, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH),
        mCalendar.get(Calendar.DAY_OF_MONTH));
    pickerDialog.show();
  }

  private class MyGridViewAdapter extends BaseAdapter {
    private int currentPosition = 0;
    public int getCurrentPosition() {
      return currentPosition;
    }

    public void setCurrentPosition(int currentPosition) {
      this.currentPosition = currentPosition;
      notifyDataSetChanged();
    }

    public MyGridViewAdapter(List<AccType>list) {
     mList=list;
    }

    @Override public int getCount() {
      return mList.size();
    }

    @Override public Object getItem(int i) {
      return i;
    }

    @Override public long getItemId(int i) {
      return i;
    }

    @Override public View getView(int position, View convertView, ViewGroup viewGroup) {
      ViewHold hold;
      if (convertView == null) {
        hold = new ViewHold();
        convertView =
            LayoutInflater.from(getActivity()).inflate(R.layout.user_cash_filter_item, null);
        hold.mTextView = convertView.findViewById(R.id.tv_name);
        convertView.setTag(hold);
      } else {
        hold = (ViewHold) convertView.getTag();
      }
      hold.mTextView.setText(mList.get(position).getAccCN());
      if (currentPosition == position) {
        hold.mTextView.setBackground(
            getActivity().getResources().getDrawable(R.drawable.selector_confirm_blue));
        hold.mTextView.setTextColor(getActivity().getResources().getColor(R.color.white));
      } else {
        hold.mTextView.setBackground(
            getActivity().getResources().getDrawable(R.drawable.selector_text_gray));
        hold.mTextView.setTextColor(getActivity().getResources().getColor(R.color.gray_99));
      }
      return convertView;
    }

    class ViewHold {
      TextView mTextView;
    }
  }

  @Override public void onDestroyView() {
    super.onDestroyView();
    unbinder.unbind();
  }
}
